package com.example.learnquartz.api;

import com.example.learnquartz.bean.AjaxResult;
import com.example.learnquartz.entity.SysJob;
import com.example.learnquartz.exception.TaskException;
import com.example.learnquartz.service.ISysJobService;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.quartz.SchedulerException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * 调度任务信息操作处理
 *
 * @author ruoyi
 */
@Controller
@RequestMapping("/monitor/job")
@Api(tags = "用户管理相关接口")
public class SysJobController {
    private ISysJobService jobService;


    public SysJobController(ISysJobService jobService) {
        this.jobService = jobService;
    }



    @PostMapping("/list")
    @ResponseBody
    @ApiOperation(value = "查询所有SysJob")
    public AjaxResult list(SysJob job) {
        List<SysJob> list = jobService.selectJobList(job);
        return AjaxResult.success(list);
    }


    @PostMapping("/remove")
    @ResponseBody
    public AjaxResult remove(String ids) throws SchedulerException {
        jobService.deleteJobByIds(ids);
        return AjaxResult.success();
    }

    @GetMapping("/detail/{jobId}")
    public AjaxResult detail(@PathVariable("jobId") Long jobId) {
        return AjaxResult.success(jobService.selectJobById(jobId));
    }

    /**
     * 任务调度状态修改
     */
    @PostMapping("/changeStatus")
    @ResponseBody
    public AjaxResult changeStatus(SysJob job) throws SchedulerException {
        SysJob newJob = jobService.selectJobById(job.getJobId());
        newJob.setStatus(job.getStatus());
        return AjaxResult.success(jobService.changeStatus(newJob));
    }

    /**
     * 任务调度立即执行一次
     */
    @PostMapping("/run")
    @ResponseBody
    public AjaxResult run(SysJob job) throws SchedulerException {
        jobService.run(job);
        return AjaxResult.success();
    }


    /**
     * 新增保存调度
     */
    @PostMapping("/add")
    @ResponseBody
    public AjaxResult addSave(@Validated SysJob job) throws SchedulerException, TaskException {
        return AjaxResult.success(jobService.insertJob(job));
    }


    /**
     * 修改保存调度
     */
    @PostMapping("/edit")
    @ResponseBody
    public AjaxResult editSave(@Validated SysJob job) throws SchedulerException, TaskException {
        return AjaxResult.success(jobService.updateJob(job));
    }

    /**
     * 校验cron表达式是否有效
     */
    @PostMapping("/checkCronExpressionIsValid")
    @ResponseBody
    public boolean checkCronExpressionIsValid(SysJob job) {
        return jobService.checkCronExpressionIsValid(job.getCronExpression());
    }
}
